package com.ddwl.message.util;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ddwl.common.exception.CommonException;
import com.ddwl.schema.bo.gate.AliYunSmsBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author Fu Zhaohui
 * @date 2017/6/21
 */
@Slf4j
@Component
public class AliYunSmsSender {

    @Value("${sms.aliyun.accessKey}")
    private String accessKey;
    @Value("${sms.aliyun.secret}")
    private String secret;
    @Value("${sms.aliyun.template.code}")
    private String codeTemplate;

    /**
     * 发送验证码
     *
     * @param mobile
     * @param code
     * @return
     */
    public void sendCode(String mobile, String code) {
        AliYunSmsBo sender = new AliYunSmsBo();
        sender.setCode(code);
        sender.setMobile(mobile);
        sender.setTemplateCode(codeTemplate);
        String content = JSON.toJSONString(sender);
        DefaultProfile profile = DefaultProfile.getProfile("default", accessKey, secret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", "福芯");
        request.putQueryParameter("TemplateCode", codeTemplate);
        request.putQueryParameter("TemplateParam", content);
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("短信发送结果{}", response.getData());
        } catch (ServerException e) {
            log.error("短信发送异常", e);
            throw new CommonException("验证码发送失败");
        } catch (ClientException e) {
            log.error("短信发送异常", e);
            throw new CommonException("验证码发送失败");
        }
    }
}
